package com.ang.juc.n4.t1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class T2 {
        private final ReentrantLock lock = new ReentrantLock();

        public void methodA() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " acquired the lock in methodA.");
                // 模拟一些工作
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                System.out.println(Thread.currentThread().getName() + " releasing the lock from methodA.");
                lock.unlock(); // 确保总是释放锁
            }
        }

        public void methodB() {
            boolean locked = false;
            try {
                locked = lock.tryLock(5, TimeUnit.SECONDS); // 尝试获取锁，等待最多5秒
                if (locked) {
                    System.out.println(Thread.currentThread().getName() + " acquired the lock in methodB.");
                    // 模拟一些工作
                    Thread.sleep(5000);
                } else {
                    System.out.println(Thread.currentThread().getName() + " failed to acquire the lock in methodB.");
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                if (locked) {
                    System.out.println(Thread.currentThread().getName() + " releasing the lock from methodB.");
                    lock.unlock(); // 确保总是释放锁
                }
            }
        }

        public static void main(String[] args) throws InterruptedException {
            T2 resource = new T2();

            Thread threadA = new Thread(() -> resource.methodA(), "Thread-A");
            Thread threadB = new Thread(() -> resource.methodB(), "Thread-B");

            threadA.start();
            // 让线程1先进入临界区
            Thread.sleep(500);
            threadB.start();

            threadA.join();
            threadB.join();
        }
}
